package com.overseasShopping.Action;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.sql.SQLException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.struts2.ServletActionContext;
import org.hibernate.Hibernate;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;

import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionSupport;
import com.overseasShopping.Biz.GoodsBiz;
import com.overseasShopping.pojo.DetailUser;
import com.overseasShopping.pojo.Goods;
import com.overseasShopping.pojo.User;
import com.overseasShopping.util.PageBean;

public class GoodsAction extends ActionSupport {

	private GoodsBiz goodsBiz;
	private Goods good;
	private File image;
	private String uploadContentType;

	public String getUploadContentType() {
		return uploadContentType;
	}

	public void setUploadContentType(String uploadContentType) {
		this.uploadContentType = uploadContentType;
	}

	public File getImage() {
		return image;
	}

	public void setImage(File image) {
		this.image = image;
	}

	public Goods getGood() {
		return good;
	}

	public void setGood(Goods good) {
		this.good = good;
	}

	public GoodsBiz getGoodsBiz() {
		return goodsBiz;
	}

	public void setGoodsBiz(GoodsBiz goodsBiz) {
		this.goodsBiz = goodsBiz;
	}

	public void getGoods() {
		PageBean<Goods> pageBean = new PageBean<Goods>();

		HttpServletRequest request = ServletActionContext.getRequest();
		HttpServletResponse response = ServletActionContext.getResponse();
		response.setContentType("text/plain;charset=UTF-8");

		String listType = request.getParameter("listTypes");
		int type = Integer.parseInt(request.getParameter("types"));
		int temp = Integer.parseInt(request.getParameter("temps"));
		int curPage = Integer.parseInt(request.getParameter("curPages"));
		int mark = Integer.parseInt(request.getParameter("toltal"));
		String search = request.getParameter("search");
		int top = Integer.parseInt(request.getParameter("top"));
		
		if(top==0){
			try {
				search = new String(search.getBytes("ISO-8859-1"), "utf-8");
			} catch (UnsupportedEncodingException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}			
		}	

		if ("#".equals(search)) {
			search = null;
		}
		pageBean.setCurrentPage(curPage);

		if (search == null || search.length() == 0) {
			if (temp == 0) {
				if (type == 0) {
					goodsBiz.getGoodsByListTypePage(listType, pageBean);
				} else {
					goodsBiz.getGoodsByListTypePage(listType, type, pageBean);
				}
			} else if (temp == 1) {
				if (type == 0) {
					goodsBiz.getGoodsByPriceUp(listType, pageBean);
				} else {
					goodsBiz.getGoodsByPriceUp(listType, type, pageBean);
				}
			} else if (temp == 2) {
				if (type == 0) {
					goodsBiz.getGoodsByPriceDwon(listType, pageBean);
				} else {
					goodsBiz.getGoodsByPriceDwon(listType, type, pageBean);
				}
			} else if (temp == 3) {
				if (type == 0) {
					goodsBiz.getRecentlyGoods(listType, pageBean);
				} else {
					goodsBiz.getRecentlyGoods(listType, type, pageBean);
				}
			}
		} else {
			if (temp == 0) {
				if (type == 0) {
					goodsBiz.getGoodsByListTypePage(listType, search, pageBean);
				} else {
					goodsBiz.getGoodsByListTypePage(listType, type, search,
							pageBean);
				}
			} else if (temp == 1) {
				if (type == 0) {
					goodsBiz.getGoodsByPriceUp(listType, search, pageBean);
				} else {
					goodsBiz.getGoodsByPriceUp(listType, type, search, pageBean);
				}
			} else if (temp == 2) {
				if (type == 0) {
					goodsBiz.getGoodsByPriceDwon(listType, search, pageBean);
				} else {
					goodsBiz.getGoodsByPriceDwon(listType, type, search,
							pageBean);
				}
			} else if (temp == 3) {
				if (type == 0) {
					goodsBiz.getRecentlyGoods(listType, search, pageBean);
				} else {
					goodsBiz.getRecentlyGoods(listType, type, search, pageBean);
				}
			}
		}

		String json = null;
		int toltal = pageBean.getTotalCount();
		List<Goods> goods = pageBean.getPageData();

		if (goods == null || goods.isEmpty() || goods.size() == 0) {
			json = null;
		} else {
			if ("sale".equals(listType)) {
				for (int i = 0; i < goods.size(); i++) {
					getImage(goods.get(i));
				}

			}
			json = getJson(goods);
		}

		try {
			PrintWriter out = response.getWriter();

			if (mark == 0) {
				out.print(toltal);
			} else {
				out.print(json);
			}
			out.flush();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	public void getHotGoods() {
		HttpServletResponse response = ServletActionContext.getResponse();
		response.setContentType("text/plain;charset=UTF-8");

		List<Goods> goods = goodsBiz.getHotGoods();
		String json = getJson(goods);

		try {
			PrintWriter out = response.getWriter();
			out.print(json);
			out.flush();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	public void getMyGoods() {
		HttpServletRequest request = ServletActionContext.getRequest();
		HttpServletResponse response = ServletActionContext.getResponse();
		response.setContentType("text/plain;charset=UTF-8");
		Map<String, Object> map = ActionContext.getContext().getSession();
		User user = (User) map.get("user");

		String listType = request.getParameter("listType");

		List<Goods> goods = new ArrayList<Goods>();

		if (listType != null && listType != "") {
			goods = goodsBiz.getGoodByUserId(user.getUserId(), listType);
		} else {
			goods = goodsBiz.getGoodByUserId(user.getUserId());
		}
		String json = null;
		if (goods == null || goods.isEmpty() || goods.size() == 0) {
			json = null;
		} else {
			json = getJson(goods);
		}

		try {
			PrintWriter out = response.getWriter();
			out.print(json);
			out.flush();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	public String updateGood() {

		Map<String, Object> map = ActionContext.getContext().getSession();
		User user = (User) map.get("user");
		DetailUser detail = user.getDetailUser();
		good.setDetailUser(detail);

		Date date = new Date();
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		String strdate = sdf.format(date);
		try {
			Date day = sdf.parse(strdate);
			good.setCreateDate(day);
		} catch (ParseException e) {
			e.printStackTrace();
		}
		if ("sale".equals(good.getListType())) {
			if (image == null) {
				String realpath = ServletActionContext.getServletContext()
						.getRealPath("/");
				System.out.println("==========  "+good.getGoodId());
				String path = realpath + "uImg/" + good.getGoodId() + ".jpg";
				image = new File(path);
			}
			InputStream in;
			try {
				in = new FileInputStream(image);
				byte[] data = new byte[(int) in.available()];
				good.setImage(Hibernate.createBlob(data));
				in.read(data);
				in.close();
			} catch (FileNotFoundException e1) {
				e1.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		image=null;
		getImage(good);
		goodsBiz.updateGoods(good);

		return SUCCESS;
	}

	public void getImage(Goods good) {
		try {
			String realpath = ServletActionContext.getServletContext()
					.getRealPath("/");
			String path = realpath + "uImg/" + good.getGoodId() + ".jpg";

			File file = new File(path);
			OutputStream out = new FileOutputStream(file);
			InputStream img = good.getImage().getBinaryStream();
			byte[] b = new byte[img.available()];
			img.read(b);
			out.write(b);
			out.flush();
			out.close();
		} catch (SQLException e1) {
			e1.printStackTrace();
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	public String addGoods() {

		Map<String, Object> map = ActionContext.getContext().getSession();
		User user = (User) map.get("user");
		DetailUser detail = user.getDetailUser();
		good.setDetailUser(detail);

		Date date = new Date();
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		String strdate = sdf.format(date);
		try {
			Date day = sdf.parse(strdate);
			good.setCreateDate(day);
		} catch (ParseException e) {
			e.printStackTrace();
		}

		if ("sale".equals(good.getListType())) {
			InputStream in;
			try {
				in = new FileInputStream(image);
				byte[] data = new byte[(int) in.available()];
				good.setImage(Hibernate.createBlob(data));
				in.read(data);
				in.close();
			} catch (FileNotFoundException e1) {
				e1.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}

		goodsBiz.addGoods(good);
		if ("sale".equals(good.getListType())) {
			List<Goods> goodn = goodsBiz.getGoodByUserId(user.getUserId(),
					"sale");
			for (int i = 0; i < goodn.size(); i++) {
				if (good.getGoodName().equals(goodn.get(i).getGoodName())) {
					getImage(goodn.get(i));
				}
			}
		}

		return SUCCESS;
	}

	// 修改状态
	public String downGood() {
		goodsBiz.fixGoodState(good.getGoodId(), 3);
		return SUCCESS;
	}

	public String turnJsp() {
		int type = good.getType();
		String name = good.getGoodName();
		String listType = good.getListType();
		Map<String, Object> map = ActionContext.getContext().getSession();
		map.put("type", type);
		map.put("search", name);
		map.put("listType", listType);
		map.remove("bb");

		if ("buy".equals(listType)) {
			return "buy";
		} else {
			return "sale";
		}
	}

	public void saveImage(Goods good) {
		InputStream in = null;
		Configuration cfg = null;
		SessionFactory sessions = null;
		Session session = null;
		Transaction tx = null;

		try {
			in = new FileInputStream(image);
			byte[] data = new byte[(int) in.available()];
			in.read(data);
			in.close();
			good.setImage(Hibernate.createBlob(data));

			cfg = new Configuration().configure();
			sessions = cfg.buildSessionFactory();
			session = sessions.openSession();
			tx = session.beginTransaction();
			session.save(good);
			tx.commit();
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			try {
				session.close();
			} catch (Exception e1) {
				e1.printStackTrace();
			}
		}
	}

	public String getJson(List<Goods> goods) {
		StringBuilder sb = new StringBuilder();
		sb.append("[");
		for (int i = 0; i < goods.size(); i++) {
			sb.append("{");
			sb.append("\"");
			sb.append("goodId");
			sb.append("\"");
			sb.append(":");
			sb.append("\"");
			sb.append(goods.get(i).getGoodId());
			sb.append("\"");
			sb.append(",");
			sb.append("\"");
			sb.append("goodName");
			sb.append("\"");
			sb.append(":");
			sb.append("\"");
			sb.append(goods.get(i).getGoodName());
			sb.append("\"");
			sb.append(",");
			sb.append("\"");
			sb.append("type");
			sb.append("\"");
			sb.append(":");
			sb.append("\"");
			sb.append(goods.get(i).getType());
			sb.append("\"");
			sb.append(",");
			sb.append("\"");
			sb.append("price");
			sb.append("\"");
			sb.append(":");
			sb.append("\"");
			sb.append(goods.get(i).getPrice());
			sb.append("\"");
			sb.append(",");
			sb.append("\"");
			sb.append("count");
			sb.append("\"");
			sb.append(":");
			sb.append("\"");
			sb.append(goods.get(i).getCount());
			sb.append("\"");
			sb.append(",");
			sb.append("\"");
			sb.append("briefing");
			sb.append("\"");
			sb.append(":");
			sb.append("\"");
			sb.append(goods.get(i).getBriefing());
			sb.append("\"");
			sb.append(",");
			sb.append("\"");
			sb.append("createDate");
			sb.append("\"");
			sb.append(":");
			sb.append("\"");
			sb.append(goods.get(i).getCreateDate());
			sb.append("\"");
			sb.append(",");
			sb.append("\"");
			sb.append("state");
			sb.append("\"");
			sb.append(":");
			sb.append("\"");
			sb.append(goods.get(i).getState());
			sb.append("\"");
			sb.append(",");
			sb.append("\"");
			sb.append("listType");
			sb.append("\"");
			sb.append(":");
			sb.append("\"");
			sb.append(goods.get(i).getListType());
			sb.append("\"");
			sb.append(",");
			sb.append("\"");
			sb.append("topImage");
			sb.append("\"");
			sb.append(":");
			sb.append("\"");
			sb.append(goods.get(i).getDetailUser().getUimage());
			sb.append("\"");
			sb.append(",");
			sb.append("\"");
			sb.append("uid");
			sb.append("\"");
			sb.append(":");
			sb.append("\"");
			sb.append(goods.get(i).getDetailUser().getUserId());
			sb.append("\"");
			sb.append(",");
			sb.append("\"");
			sb.append("sign");
			sb.append("\"");
			sb.append(":");
			sb.append("\"");
			sb.append(goods.get(i).getDetailUser().getSignature());
			sb.append("\"");
			sb.append(",");
			sb.append("\"");
			sb.append("credit");
			sb.append("\"");
			sb.append(":");
			sb.append("\"");
			sb.append(goods.get(i).getDetailUser().getCredit());
			sb.append("\"");
			sb.append(",");
			sb.append("\"");
			sb.append("userName");
			sb.append("\"");
			sb.append(":");
			sb.append("\"");
			sb.append(goods.get(i).getDetailUser().getNickName());
			sb.append("\"");
			sb.append("}");
			sb.append(",");
		}
		sb.deleteCharAt(sb.length() - 1);
		sb.append("]");

		return sb.toString();
	}

}
